package cn.tedu.weibo.controller;

import cn.tedu.weibo.mapper.WeiboMapper;
import cn.tedu.weibo.pojo.dto.WeiboDTO;
import cn.tedu.weibo.pojo.entity.Weibo;
import cn.tedu.weibo.pojo.vo.UserVO;
import cn.tedu.weibo.pojo.vo.WeiboDetailVO;
import cn.tedu.weibo.pojo.vo.WeiboIndexVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/weibo/")
public class WeiboController {
    @Autowired(required = false)
    WeiboMapper mapper;

    @RequestMapping("insert")
    public int insert(@RequestBody WeiboDTO weiboDTO, HttpSession session) {
        //从会话对象中得到登录成功时保存的用户对象
        UserVO user = (UserVO) session.getAttribute("user");
        if (user == null) {//未登录
            return 2;
        }
        Weibo w = new Weibo();
        //复制属性
        BeanUtils.copyProperties(weiboDTO, w);
        w.setCreated(new Date());
        //设置微博对象中用户id为当前登录的用户id
        w.setUserId(user.getId());
        mapper.insert(w);
        return 1;
    }
    @RequestMapping("selectIndex")
    public List<WeiboIndexVO> selectIndex(){
        return mapper.selectIndex();
    }
    @RequestMapping("selectById")
    public WeiboDetailVO selectById(int id){
        return mapper.selectById(id);
    }
}
